﻿using ChuanYe.CountyFireManagement.EF.MySQL.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using ChuanYe.CountyFireManagement.Model;
using System.Transactions;
using Microsoft.EntityFrameworkCore;
using ChuanYe.Core.Utils;
using ChuanYe.CountyFireManagement.EF.MySQL;

namespace ChuanYe.CountyFireManagement.BLL
{
    public class FireTeamResponseBLL
    {
        #region 构造单例
        private FireTeamResponseBLL() { }
        private static FireTeamResponseBLL _instance;
        public static FireTeamResponseBLL Instance
        {
            get
            {
                return _instance ?? (_instance = new FireTeamResponseBLL());
            }
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="teamDepartmentId"></param>
        /// <param name="phoneIsNull">手机是否可以为空</param>
        /// <returns></returns>
        public List<Fireteamdepartment> GetTeamDepartment(int teamDepartmentId,bool phoneIsNull) 
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var linq = from a in ef.Fireteamdepartment select a;
                if (teamDepartmentId > 0)
                {
                    linq = linq.Where(p => p.TeamDepartmentId == teamDepartmentId);
                }
                if (!phoneIsNull)
                {
                    linq = linq.Where(p => p.Phone!=null&& p.Phone!=string.Empty);
                }
                return linq.ToList();
            }
        }

        public ResultDto<List<FireMQTTResponseModel>> Add(List<Fireteamresponse> infos)
        {
            ResultDto<List<FireMQTTResponseModel>> result = new ResultDto<List<FireMQTTResponseModel>>();
            var fireInfo = BLL.FireInfoBLL.Instance.Get(infos[0].FireId);
            if (fireInfo == null)
            {
                result.Status = -1;
                result.Message = "FireInfo Is Not Exist";
                return result;
            }
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                List<string> names = new List<string>();
                List<int> tempResponseIds = new List<int>();
                foreach (var item in infos)
                {
                    string content = string.Format(FireInfoTool.GetFireInfoMessageFormat((int)MessageType.联动响应),
                                                         fireInfo.FireName);
                    item.TeamResponseContent = content;
                    ef.Fireteamresponse.Add(item);
                    ef.Entry<Fireteamresponse>(item).State = EntityState.Added;
                    ef.SaveChanges();
                    var existTeamDepartment = ef.Fireteamdepartment.Where(p => p.TeamDepartmentId == item.TeamDepartmentId).FirstOrDefault();
                    if (existTeamDepartment != null)
                    {
                        names.Add(existTeamDepartment.Name);
                    }
                    tempResponseIds.Add(item.TeamResponseId);
                }
                if (infos.Count > 0)
                {
                    var userInfo = ef.Userinfo.Where(p => p.UserId == infos[0].UserId).FirstOrDefault();
                    //处置记录
                    Record record = new Record();
                    record.FireId = fireInfo.FireId;
                    record.HandleTime = infos.FirstOrDefault().TransDatetime;
                    record.Type = (int)RecordType.联动响应;
                    record.UserId = infos.FirstOrDefault().UserId;
                    string joinNames = string.Join(",", names);
                    record.Content = string.Format(FireInfoTool.GetFireInfoRecordFormat(record.Type.Value), joinNames, names.Count);
                    record.AddTime = infos.FirstOrDefault().TransDatetime;
                    record.Ip = infos.FirstOrDefault().Ip;
                    record.Applicant = userInfo.RealName;
                    record.CustomData = string.Join(",", tempResponseIds);
                    ef.Record.Add(record);
                    ef.Entry<Record>(record).State = EntityState.Added;

                    Message message = new Message();
                    message.FireId = fireInfo.FireId;
                    message.Type = (int)MessageType.联动响应;
                    message.Content = $"{userInfo.RealName}已部署联动响应单位";
                    message.SendType = (int)MessageSendType.上级向下级发送;
                    message.IsRead = 0;
                    message.HandleTime = fireInfo.HappenDatetime;
                    message.Ip = fireInfo.Ip;
                    ef.Message.Add(message);
                    ef.Entry<Message>(message).State = EntityState.Added;
                    ef.SaveChanges();

                    #region 装载消息
                    List<Message> messages = new List<Message>() { message };
                    result.FirstParam = MessageBLL.Instance.TransMessageToFireMQTTResponseModel(messages, (int)record.Type);
                    #endregion
                }
            }
            return result;
        }

        public int AddTeamDepartment(Fireteamdepartment info)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                if (info.Sort==0)
                {
                    var maxSortInfo = ef.Fireteamdepartment.OrderByDescending(o => o.Sort).FirstOrDefault();
                    if (maxSortInfo != null)
                    {
                        info.Sort = maxSortInfo.Sort + 1;
                    }
                    else
                    {
                        info.Sort = 1;
                    }
                }
                int isAdd = ef.Fireteamdepartment.Where(p => p.Name == info.Name).ToList().Count();
                if (isAdd != 0)
                {
                    return -2;
                }
                ef.Fireteamdepartment.Add(info);
                ef.Entry<Fireteamdepartment>(info).State = EntityState.Added;
                return ef.SaveChanges();
            }
        }

        public int UpdateTeamDepartment(Fireteamdepartment info)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var exist = ef.Fireteamdepartment.Where(p => p.TeamDepartmentId == info.TeamDepartmentId).FirstOrDefault();
                if (exist == null)
                {
                    return -1;
                }
                else
                {
                    int isUpdate = ef.Fireteamdepartment.Where(p =>p.TeamDepartmentId!=info.TeamDepartmentId && p.Name == info.Name).ToList().Count();
                    if (isUpdate != 0)
                    {
                        return -2;
                    }

                    exist.TeamDepartmentId = info.TeamDepartmentId;
                    exist.Name = info.Name;
                    exist.Ip = info.Ip;
                    exist.Phone = info.Phone;
                    exist.Remarks = info.Remarks;
                    exist.Sort = info.Sort;
                    exist.Tel = info.Tel;
                    exist.UserId = info.UserId;
                    exist.TransDatetime = info.TransDatetime;
                    ef.Fireteamdepartment.Add(exist);
                    ef.Entry<Fireteamdepartment>(exist).State = EntityState.Modified;
                    return ef.SaveChanges();
                }
            }
        }

        public ResultDto<dynamic, dynamic> GetFireTeamDepartmentByPage(RequestPageBase page)
        {
            ResultDto<dynamic, dynamic> result = new ResultDto<dynamic, dynamic>();
            var sql = AppSetting.GetConfig("Sql:BasicSelect");
            sql = string.Format(sql, "fireteamdepartment");
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                string paramsSql = string.Empty;
                if (!string.IsNullOrEmpty(page.Keyword))
                {
                    paramsSql += $"  Name like '%{page.Keyword}%'";
                    paramsSql += $" or Phone like '%{page.Keyword}%'";
                    paramsSql += $" or Tel like '%{page.Keyword}%'";
                    paramsSql = $" and ({paramsSql})";
                }

                paramsSql += page.OrderByPattern == 0 ? "Sort".OrderByDescending() : "Sort".OrderBy();
                paramsSql += page.Limit();
                sql += paramsSql;
                var countSql = sql.CountSql();
                var list = ef.Database.SqlQuery<Fireteamdepartment>(sql);
                result.FirstParam = list;
                result.SecondParam = ef.Database.SqlQuery(countSql).Rows[0][0];
            }
            return result;
        }

        public int RemoveTeamDepartment(int teamDepartmentId)
        {
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var exist = ef.Fireteamdepartment.Where(p => p.TeamDepartmentId == teamDepartmentId).FirstOrDefault();
                if (exist == null)
                {
                    return -1;
                }
                var existFireteamresponse = ef.Fireteamresponse.Where(p => p.TeamDepartmentId == teamDepartmentId).FirstOrDefault();
                if (existFireteamresponse != null)
                {
                    return -2;
                }
                var existFireHeadquartermember = ef.Fireheadquartermember.Where(p => p.TeamDepartmentId == teamDepartmentId).FirstOrDefault();
                if (existFireteamresponse != null)
                {
                    return -3;
                }

                ef.Fireteamdepartment.Add(exist);
                ef.Entry<Fireteamdepartment>(exist).State = EntityState.Deleted;
                return ef.SaveChanges();
            }
        }
    }
}
